import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Chip,
  Button,
  Divider,
  IconButton,
  Breadcrumbs,
  Link,
  CircularProgress,
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  LocalOffer as TagIcon,
  Category as CategoryIcon,
  ArrowBack as ArrowBackIcon,
  Star as StarIcon,
} from '@mui/icons-material';
import ReactMarkdown from 'react-markdown';
import axios from 'axios';

const KnowledgeDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [knowledge, setKnowledge] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchKnowledge = async () => {
      setLoading(true);
      try {
        const response = await axios.get(`/api/knowledge/${id}`);
        setKnowledge(response.data);
        setError(null);
      } catch (err) {
        console.error('获取知识条目失败:', err);
        setError('获取知识条目失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchKnowledge();
  }, [id]);

  const handleEdit = () => {
    navigate(`/knowledge/edit/${id}`);
  };

  const handleDelete = async () => {
    if (!window.confirm('确定要删除这个知识条目吗？')) return;

    try {
      await axios.delete(`/api/knowledge/${id}`);
      navigate('/');
    } catch (err) {
      console.error('删除知识条目失败:', err);
      alert('删除失败，请稍后重试');
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ textAlign: 'center', py: 4 }}>
        <Typography variant="h6" color="error">
          {error}
        </Typography>
        <Button variant="contained" onClick={handleBack} sx={{ mt: 2 }}>
          返回
        </Button>
      </Box>
    );
  }

  if (!knowledge) return null;

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
        <IconButton onClick={handleBack} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Breadcrumbs aria-label="breadcrumb">
          <Link color="inherit" onClick={() => navigate('/')} sx={{ cursor: 'pointer' }}>
            首页
          </Link>
          {knowledge.category && (
            <Link 
              color="inherit" 
              onClick={() => navigate(`/category/${knowledge.category.id}`)} 
              sx={{ cursor: 'pointer' }}
            >
              {knowledge.category.name}
            </Link>
          )}
          <Typography color="text.primary">{knowledge.title}</Typography>
        </Breadcrumbs>
      </Box>

      <Paper elevation={1} sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
          <Typography variant="h4" component="h1" gutterBottom>
            {knowledge.title}
          </Typography>
          <Box>
            <IconButton onClick={handleEdit} color="primary">
              <EditIcon />
            </IconButton>
            <IconButton onClick={handleDelete} color="error">
              <DeleteIcon />
            </IconButton>
          </Box>
        </Box>

        <Box sx={{ display: 'flex', gap: 1, mb: 2, flexWrap: 'wrap' }}>
          {knowledge.category && (
            <Chip
              icon={<CategoryIcon />}
              label={knowledge.category.name}
              variant="outlined"
              onClick={() => navigate(`/category/${knowledge.category.id}`)}
            />
          )}
          {knowledge.tags && knowledge.tags.map((tag) => (
            <Chip
              key={tag.id}
              icon={<TagIcon />}
              label={tag.name}
              variant="outlined"
              onClick={() => navigate(`/?tag_id=${tag.id}`)}
            />
          ))}
          <Box sx={{ ml: 'auto', display: 'flex', alignItems: 'center' }}>
            {Array(knowledge.importance).fill().map((_, i) => (
              <StarIcon key={i} color="warning" />
            ))}
          </Box>
        </Box>

        <Box sx={{ display: 'flex', justifyContent: 'space-between', color: 'text.secondary', fontSize: '0.875rem', mb: 2 }}>
          <Box>创建时间: {new Date(knowledge.created_at).toLocaleString()}</Box>
          <Box>更新时间: {new Date(knowledge.updated_at).toLocaleString()}</Box>
          <Box>浏览次数: {knowledge.views}</Box>
        </Box>

        <Divider sx={{ my: 2 }} />

        <Box className="markdown-content" sx={{ mt: 2 }}>
          <ReactMarkdown>{knowledge.content}</ReactMarkdown>
        </Box>

        {knowledge.source && (
          <Box sx={{ mt: 3, pt: 2, borderTop: '1px solid #eee' }}>
            <Typography variant="subtitle2" color="text.secondary">
              来源: {knowledge.source}
            </Typography>
          </Box>
        )}

        {knowledge.attachments && (
          <Box sx={{ mt: 3 }}>
            <Typography variant="subtitle1" gutterBottom>
              附件
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {JSON.parse(knowledge.attachments).map((attachment, index) => (
                <Chip
                  key={index}
                  label={attachment.name}
                  onClick={() => window.open(attachment.url, '_blank')}
                  variant="outlined"
                />
              ))}
            </Box>
          </Box>
        )}
      </Paper>
    </Box>
  );
};

export default KnowledgeDetail;